#include "app_uart.h"

#include "app_flash.h"
#include "app_work.h"
#include "bsp_motor.h"
#include "bsp_uart_fifo.h"

// UART APP Init
void app_uart_init(void) {}

void app_uart_data_parse(uint8_t cmd, uint8_t len, uint8_t *buf) {
  switch (cmd) {
    case SET_DEV_WORK_STA:
     if((app_cfg_work_info()->workStep!=WORK_IDLE)&&(app_cfg_work_info()->workStep!=WORK_STOP)&&(buf[0]>0)){
       break;
     }
      app_cfg_work_info()->workStep = buf[0];
      bsp_uart_send_byte(0, buf[0]);
      break;
    case SET_DEV_SWEEP_SPEED:
      app_user_flash_get()->dev_sweep_speed = buf[0];
      bsp_mot_set_step(BRUSH_MOTOR_GN, app_user_flash_get()->dev_sweep_speed);
      app_user_flash_save();
      break;
    case SET_DEV_X_STEP:
      app_user_flash_get()->dev_x_step = buf[0];
      bsp_mot_set_step(X_MOTOR_GN, app_user_flash_get()->dev_x_step);
      app_user_flash_save();
      break;
    case SET_DEV_Y_STEP:
      app_user_flash_get()->dev_y_step = buf[0];
      bsp_mot_set_step(Y_MOTOR_GN, app_user_flash_get()->dev_y_step);
      app_user_flash_save();
      break;

    case SET_DEV_Y_TIME:
      app_user_flash_get()->dev_Y_step_Time = buf[0];
      app_user_flash_save();
      break;
    default:
      break;
  }
}

// 帧头+数据长度+CMD+数据体+校验码
void app_uart_loop(void) {
  uint8_t message_len = 0;
  uint8_t message_cmd = 0;
  uint8_t i = 0;
  uint8_t data_buf[16] = {0};
  UART_ST *pUart = NULL;
  pUart = bsp_uart_get_parm(UART0_NUM);

  while ((pUart->pRxWrite + UART_RX_BUF_LEN - pUart->pRxRead) %
             UART_RX_BUF_LEN >
         3) {
    if (pUart->rxBuf[pUart->pRxRead] == MESSAGE_HAND) {
      message_len = pUart->rxBuf[(pUart->pRxRead + 1) % UART_RX_BUF_LEN];
      message_cmd = pUart->rxBuf[(pUart->pRxRead + 2) % UART_RX_BUF_LEN];
      // message recv handler function
      if (message_len > 16) {
        message_len = 16;
      }

      for (i = 0; i < message_len; i++) {
        data_buf[i] = pUart->rxBuf[(pUart->pRxRead + 3 + i) % UART_RX_BUF_LEN];
      }
      app_uart_data_parse(message_cmd, message_len, data_buf);
      pUart->pRxRead += message_len;
      pUart->pRxRead += 3;
      pUart->pRxRead %= UART_RX_BUF_LEN;

    } else {
      pUart->pRxRead++;
      pUart->pRxRead %= UART_RX_BUF_LEN;
    }
  }
}
